#include <iostream>
#include <memory>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "inetAddr.hpp"

using namespace LogModule;

const std::string sep = ": ";
const std::string defaultdict = "./dictionary";

class Dict{
public:
    Dict(std::string path = defaultdict)
        :_dict_path(path)
    {}

    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::FATAL) << "字典打开失败";
            return false;
        }
        std::string line;
        while(std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "解析词语" << line << "失败";
                continue;
            }

            std::string english = line.substr(0, pos);
            std::string chinses = line.substr(pos + sep.size());

            if(english.empty() || chinses.empty())
            {
                LOG(LogLevel::WARNING) << "解析" << line << "失败";
                continue;
            }

            _dict.insert(make_pair(english, chinses));

        }
        in.close();
        return true;
    }

    std::string Tranlate(const std::string& word, InetAddr& client)
    {   
        auto iter = _dict.find(word);
        if(iter == _dict.end()){
            LOG(LogLevel::DEBUG) << "进入到翻译模块: " << "[" << client.Ip() << " : " << client.Port() << "]#" << word  << "->" << "None"; 
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入到翻译模块: [" << client.Ip() << " : " << client.Port() << "]#" << word << "->" << iter->second;
        return iter->second;
    }

    ~Dict()
    {}
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};
